package com.zhuangjie.mvc.ws.core;

import com.alibaba.fastjson.JSON;
import com.zhaungjie.base.utils.ReflectionUtils;
import lombok.Data;
import org.springframework.web.socket.TextMessage;

import java.util.HashMap;
import java.util.Map;

public class TextMessageParser {
    @Data
    public static class TextMessageBody<T> {
        private String request;
        private T message;
    }
    private static final  String REQUEST_KEY = "path";

    private static final String MESSAGE_KEY = "message";

    private String tryGetMessageRequestSuffix(Object body) {
        Object requestSuffix = "";
        if (body instanceof Map) {
            requestSuffix = ((Map<String, Object>) body).get(REQUEST_KEY);
        } else if (body != null) {
            requestSuffix = ReflectionUtils.getFieldValueFromObject(body, REQUEST_KEY);
        }
        if (requestSuffix == null || !(requestSuffix instanceof String)) {
            return "";
        }
        return (String) requestSuffix;
    }
    public static<T> TextMessageBody<T> parse(TextMessage textMessage,Class<T> clazz){
        HashMap<String, Object> bodyMap = JSON.parseObject(textMessage.getPayload(), HashMap.class);
        TextMessageBody<T> result = new TextMessageBody<>();
        if (bodyMap.containsKey(REQUEST_KEY)) {
            Object messageJsonStr = bodyMap.get(MESSAGE_KEY);
            // 如果messageJsonStr不是String类型，需要先转为字符串
            if (!(messageJsonStr instanceof String)) {
                messageJsonStr = JSON.toJSONString(messageJsonStr);
            }
            // 将字符串JSON转为想要的类型
            Object requestPath = bodyMap.get(REQUEST_KEY);
            result.setRequest(requestPath instanceof String ? (String) requestPath : null);
            result.setMessage(JSON.parseObject((String) messageJsonStr, clazz));
        }else {
            result.setMessage(JSON.parseObject(textMessage.getPayload(),clazz));
        }
        return result;
    }
}
